import datetime
import os
import time

import pyautogui
import redis

from utils import getTextPosition, click, scroll, find_window_position_and_check_foreground, screenshot, getWalletPosition, getWalletInfo, is_similar, scrollWalletHeight, saveWalletList, close

walletText = "拼手气红包"

def start(r1):

    # 0：不抢就等待20秒
    # 1： 抢不等待
    isRob = r1.get("isRob") or '0'
    # 发现红包等待的时常
    stopSeconds = r1.get("stopSeconds") or '15'
    ## 获取窗口信息
    window = find_window_position_and_check_foreground("QQ")
    windowX, windowY, windowWidth, windowHeight, isForeground = window

    # 找到了窗口
    if windowX > -1 and windowY > -1 and windowWidth > -1 and windowHeight > -1:
        # 窗口在前端才开始
        if isForeground:
            # 计算红包的位置
            walletInfo = getWalletInfo(windowX, windowY, windowWidth, windowHeight)
            # 检测窗口是否包含红包
            windowInfo = getTextPosition(walletText, windowX, windowY, windowWidth, windowHeight, 'windowInfo')
            # 找到了红包
            if windowInfo[0] > -1:
                # 不开抢
                if isRob != "1":
                    print(f"不抢  等待：{stopSeconds}")
                    time.sleep(int(stopSeconds))
                    # 点击红包
                    click(windowX + windowInfo[0], windowY + windowInfo[1])
                    detailInfo = getTextPosition("查看领取详情", walletInfo[0], walletInfo[1], walletInfo[2],walletInfo[3], 'walletInfo')
                    # 通过他来判断是否红包打开了
                    if detailInfo[0] == -1:
                        for i in range(1,10):
                            detailInfo = getTextPosition("查看领取详情", walletInfo[0], walletInfo[1], walletInfo[2], walletInfo[3], 'walletInfo')
                            if detailInfo[0] > -1:
                                break

                    if detailInfo[0] == -1:
                        print("红包未打开，请检查程序，本次将忽略该红包")
                    else:
                        #点击：查看领取详情
                        click(walletInfo[0] + detailInfo[0] + int(detailInfo[2] / 2), walletInfo[1] + detailInfo[1] + int(detailInfo[3] / 2))
                        listInfo = getTextPosition("发出的" + walletText, walletInfo[0], walletInfo[1], walletInfo[2],walletInfo[3], 'walletInfo1')
                        # 说明上面的点击没有打开红包详情
                        if listInfo[0] == -1:
                            for i in range(1,10):
                                click(walletInfo[0] + detailInfo[0] + int(detailInfo[2] / 2),walletInfo[1] + detailInfo[1] + int(detailInfo[3] / 2))
                                listInfo = getTextPosition("发出的" + walletText, walletInfo[0], walletInfo[1], walletInfo[2], walletInfo[3], 'walletInfo1')


                        # 红包详情已打开，执行下面的逻辑进行截图
                        if listInfo[0] > -1:
                            folder = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
                            prev_image_path = saveWalletList(walletInfo[0], walletInfo[1], walletInfo[2], walletInfo[3],folder, "1")
                            for i in range(2, 15):
                                scrollWalletHeight(i)
                                current_image_path = saveWalletList(walletInfo[0], walletInfo[1], walletInfo[2], walletInfo[3], folder, i)
                                if current_image_path and is_similar(prev_image_path, current_image_path):
                                    print("🚩 已经滚动到底部，停止截图")
                                    os.remove(current_image_path)
                                    break
                                else:
                                    prev_image_path = current_image_path

                            # 截图完毕，点击红包右上角的关闭图标
                            close(walletInfo[0] + walletInfo[2] - 30, walletInfo[1] + 8, folder, windowHeight)
                        else:
                            print("红包详情未打开，请检查程序，本次将忽略该红包")
                            # 点击红包右上角的关闭图标
                            close(walletInfo[0] + walletInfo[2] - 30, walletInfo[1] + 8, "-1", windowHeight)
                    scroll(-1 * int(windowHeight / 2))
                else:
                    # 点击红包 就是开抢
                    click(windowX + windowInfo[0], windowY + windowInfo[1])
                    # 关闭右上角的关闭按钮
                    close(walletInfo[0] + walletInfo[2] - 30, walletInfo[1] + 8, "-1", windowHeight)
                    # 暂停0.2秒，因为发现有时候，执行关闭窗口不会滑动
                    time.sleep(0.2)
                    pyautogui.scroll(-1*windowHeight)
            else:
                # 没找到，滚动窗口继续查找
                print("没找到，滚动窗口继续查找")
                time.sleep(0.2)
                scroll(-1 * int(windowHeight/2))
        else:
            print("请注意：窗口不在前台，暂停1分钟")
            time.sleep(10)



if __name__ == "__main__":
    # 连接redis
    while True:
        r = redis.Redis(host='localhost', port=6379, decode_responses=True)
        parse = r.get("parse") or b'0'
        print(f"是否许需要解析的判断：{parse}")
        if parse == "0":
            # 暂停解析
            print('暂停解析，睡眠5秒')
            time.sleep(5)
        else:
            try:
                start(r)
            except Exception as e:
                print("error:", e)